from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from apps.learning_path.models import KnowledgeNode
from apps.learning_path.neo4j_service import sync_knowledge_node, sync_prerequisites


class Command(BaseCommand):
    help = "Resync all Django knowledge nodes and their prerequisites into Neo4j."

    def handle(self, *args, **options):
        if not settings.NEO4J_URI or not settings.NEO4J_PASSWORD:
            raise CommandError("Neo4j 未配置完整 (需要 NEO4J_URI 与 NEO4J_PASSWORD)。")

        queryset = KnowledgeNode.objects.prefetch_related("prerequisites")
        total = queryset.count()

        if total == 0:
            self.stdout.write("数据库中没有知识节点，无需同步。")
            return

        self.stdout.write(f"准备同步 {total} 个知识节点到 Neo4j ...")

        for idx, node in enumerate(queryset, start=1):
            sync_knowledge_node(node)
            sync_prerequisites(node, node.prerequisites.values_list("id", flat=True))
            if idx % 20 == 0 or idx == total:
                self.stdout.write(f"- 已处理 {idx}/{total} 个节点")

        self.stdout.write(self.style.SUCCESS("Neo4j 同步完成。"))
